import 'dart:typed_data';

import 'package:flutter/cupertino.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter_09_game/config/app_config.dart';
import 'package:flutter_09_game/generated/locales.g.dart';
import 'package:flutter_09_game/utils/loading/loading_utils.dart';
import 'package:flutter_09_game/utils/permisson/permission_utils.dart';
import 'package:get/get.dart';

import 'package:image_gallery_saver_plus/image_gallery_saver_plus.dart';
import 'package:permission_handler/permission_handler.dart';
import 'dart:ui' as ui;
class UtilImage {
  /// 保存图片到相册
 static Future<void> saveImageToGallery(GlobalKey repaintBoundaryKey) async {
    try {

      // 检查存储权限
      bool hasPermission = await PermissionUtils.checkPermission(Permission.photos);
      if (!hasPermission) {
        LoadingUtils.showToast(LocaleKeys.needPhotoPermission.tr );
        return;
      }

      LoadingUtils.showLoading(status: LocaleKeys.generatingQrCode.tr);

      // 获取RepaintBoundary的RenderRepaintBoundary
      RenderRepaintBoundary boundary = repaintBoundaryKey.currentContext!
          .findRenderObject() as RenderRepaintBoundary;

      // 将Widget转换为图片
      ui.Image image = await boundary.toImage(pixelRatio: 3.0);
      ByteData? byteData = await image.toByteData(format: ui.ImageByteFormat.png);
      Uint8List pngBytes = byteData!.buffer.asUint8List();

      // 保存到相册
      final result = await ImageGallerySaverPlus.saveImage(
        pngBytes,
        quality: 100,
        name: "${AppConfig.appName}${LocaleKeys.inviteCode.tr}_${DateTime.now().millisecondsSinceEpoch}",
      );

      LoadingUtils.dismiss();

      if (result['isSuccess'] == true) {
        LoadingUtils.showToast(LocaleKeys.imageSaveSuccess.tr);
      } else {
        LoadingUtils.showToast(LocaleKeys.imageSaveFailed.tr);
      }
    } catch (e) {
      LoadingUtils.dismiss();
      LoadingUtils.showToast('${LocaleKeys.saveFailed.tr} $e');
    }
  }
}